package com.oocl.web;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.RequestContext;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

import oocl.com.WebDataHandle.impl.WebDataHandleImpl;
import oocl.com.dao.UserDao;
import oocl.com.dao.impl.UserDaoImpl;
import oocl.com.filter.impl.DataFilterImpl;
import oocl.com.pojo.User;

/**
 * Servlet implementation class WebServlet
 */
public class WebServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		WebDataHandleImpl impl = new WebDataHandleImpl();
		UserDao dao = new UserDaoImpl();
		DataFilterImpl filter = new DataFilterImpl();
		String uname = request.getParameter("uname");
		String sal = request.getParameter("sal");
		String birth = request.getParameter("birth");
		String sex = request.getParameter("sex");
		
		if(!filter.dataFilter(uname + ":" + sal + ":" + birth + ":" + sex)){
			response.sendRedirect("error");
//			response.sendRedirect("/submit");
		}
		else{
			Date date = null;
			SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy/MM/dd");
			try {
				date =  sdFormatter.parse(birth);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			User c = new User(uname, Double.parseDouble(sal), date, Integer.parseInt(sex));
			dao.addUser(c);
			response.setContentType("text/html; charset=UTF-8");
			PrintWriter writer = response.getWriter();
			writer.write(impl.createWebPage());
			writer.close();
		}
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
//		DiskFileItemFactory factory=new DiskFileItemFactory(20*1024, new File("test"));
//		ServletFileUpload upload=new ServletFileUpload(factory);
//		upload.setSizeMax(100*1024);
//		
//		try {
//			List<FileItem> items= upload.parseRequest(req);
//			for(FileItem item:items){
//				if(item.isFormField()){
//					System.out.println(item.getFieldName()+"..."+item.getString());
//				}
//				else{
//					System.out.println(item.getName()+"...."+item.getSize());
//					InputStream fin=item.getInputStream();
//				}
//			}
//			
//		} catch (FileUploadException e) {
//			e.printStackTrace();
//		}
	}
}
